package com.shenhaofeng.app.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.shenhaofeng.app.R;


/**
 * 矩形布局,可调整高度相对于宽度的比例,默认为正方形
 * Created by Administrator on 2016/5/3.
 */
public class RectLayout extends FrameLayout {


    private float ratio = 1.0f;


    public RectLayout(Context context) {
        this(context, null);
    }


    public RectLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public RectLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.RectLayout, defStyleAttr, 0);
        ratio = ta.getFloat(R.styleable.RectLayout_rect_ratio, ratio);
        ta.recycle();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthSpec;
        int heightSpec;

        if (widthMode == MeasureSpec.EXACTLY) {
            widthSpec = widthMeasureSpec;
            heightSpec = MeasureSpec.makeMeasureSpec((int) (widthSize * ratio), MeasureSpec.EXACTLY);
        } else {
            widthSpec = widthMeasureSpec;
            heightSpec = heightMeasureSpec;
        }
        super.onMeasure(widthSpec, heightSpec);
    }
}
